<?php
namespace app\common\model;

use think\Model;
use think\Validate;

class UserLevel extends Model
{
	public function checkLevel($data)
	{	
		$rules = [
						'level_name|等级名称'  => 'require',
						'amount|消费额度'   => 'require|egt:0|number',
						'discount|折扣率'   => 'require|between:1,100',
						];
		$msg = [
						'level_name.require' => '等级名称不能为空',
						'amount.require' => '消费额度不能为空',
						'amount.egt' => '消费额度必须大于等于0',
						'amount.number' => '消费额度必须是数字',
						'discount.require' => '折扣率不能为空',
						'discount.between'     => '折扣率不能在1-100之外',
						];
		$validate=new Validate($rules,$msg);
		$result   = $validate->check($data);
		if (!$result) {
				$msg['code'] = 0;
				$msg['msg']  = $validate->getError();
				return $msg;
			} else {
				return false;
			}
	}
    public function showLevel()
    {
        $data = $this->order('listorder desc')->select();
        return $data;
    }

    public function levelAdd($data, $id = '')
    {
        $this->data([
            'level_name'  => $data['level_name'],
            'amount'      => $data['amount'],
            'discount'    => $data['discount'],
            'description' => $data['description'],
        ]);
        if ($id) {
            $map['level_id'] = $id;
            $res             = $this->where($map)->update($data);
            $info = '修改';
        } else {
            $this->save();
            $res = $this->level_id;
            $info = '新增';
        }
        if ($res) {
            $msg['code'] = 1;
            $msg['msg']  = $info.'成功！';
        } else {
            $msg['code'] = 0;
            $msg['msg']  = $info.'失败！';
        }
        return $msg;
    }

    public function getLevelById($id)
    {
        $data = $this->get($id);
        return $data;
    }
}
